package top.techqi.usbd.desc

import top.techqi.core.kext.WORD_T
import top.techqi.core.util.FmtUtil

class ConfigDesc(
    val wTotalLength: Short,
    val bNumInterfaces: Byte,
    val bConfigurationValue: Byte,
    val iConfiguration: Byte,
    val bmAttributes: Byte,
    val bMaxPower: Byte
) : AbstractDesc(LENGTH, TYPE) {
    constructor(bytes: ByteArray) : this(
        WORD_T(bytes[3], bytes[2]),
        bytes[4],
        bytes[5],
        bytes[6],
        bytes[7],
        bytes[8]
    ) {
        require(bytes[0] == LENGTH && bytes[1] == TYPE) {
            "Invalid length or type: ${bytes[0]}, ${bytes[1]}"
        }
    }

    override fun toString(): String {
        return """
        ConfigDesc(
            wTotalLength      = %1${'$'}s,
            bNumInterfaces    = %2${'$'}s,
            bConfigurationValue = %3${'$'}s,
            iConfiguration    = %4${'$'}s,
            bmAttributes      = %5${'$'}s,
            bMaxPower         = %6${'$'}s
        )
        """.trimIndent().format(
            wTotalLength,
            bNumInterfaces,
            bConfigurationValue,
            iConfiguration,
            FmtUtil.toBinString(bmAttributes),
            bMaxPower
        )
    }

    companion object {
        const val TYPE: Byte = 0x02
        const val LENGTH: Byte = 9
    }
}
